package com.smartwrite.controller;

import com.smartwrite.dto.ReportGenerationRequest;
import com.smartwrite.dto.TaskResponse;
import com.smartwrite.service.ReportGenerationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 报告生成控制器
 * 负责处理报告生成相关的HTTP请求
 */
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class ReportController {

    @Autowired
    private ReportGenerationService reportGenerationService;

    /**
     * 生成报告接口
     * @param request 报告生成请求参数
     * @return 任务响应信息
     */
    @PostMapping("/generate-report")
    public ResponseEntity<TaskResponse> generateReport(@RequestBody ReportGenerationRequest request) {
        // 验证必填字段
        if (request.getPrompt() == null || request.getPrompt().trim().isEmpty()) {
            return ResponseEntity.badRequest()
                .body(new TaskResponse(null, "error", "缺少必填字段: prompt"));
        }
        
        if (request.getModel() == null || request.getModel().trim().isEmpty()) {
            return ResponseEntity.badRequest()
                .body(new TaskResponse(null, "error", "缺少必填字段: model"));
        }
        
        if (request.getApiKeys() == null || request.getApiKeys().isEmpty()) {
            return ResponseEntity.badRequest()
                .body(new TaskResponse(null, "error", "缺少必填字段: apiKeys"));
        }

        // 设置默认值
        if (request.getEnableSearch() == null) {
            request.setEnableSearch(true);
        }
        if (request.getSearchEngine() == null || request.getSearchEngine().trim().isEmpty()) {
            request.setSearchEngine("google");
        }

        try {
            // 调用服务层生成报告
            TaskResponse response = reportGenerationService.generateReport(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(new TaskResponse(null, "error", "报告生成失败: " + e.getMessage()));
        }
    }
}